<template>
  <div class="lg-collapse" :class="{ 'lg-collapse-fold': !expanded }">
    <div v-if="!disabledTitle" class="lg-collapse-header" @click="clickTitle">
      <slot name="title" :expanded="expanded" :change="change">
        {{ title }}
      </slot>
      <span v-if="!disabled" class="lg-collapse-right" :title="expanded ? '点击收起' : '点击展开'" @click.stop="change">
        <slot name="right" :expanded="expanded" :change="change">
          <chevron-down-icon v-if="expanded" />
          <chevron-right-icon v-else />
        </slot>
      </span>
    </div>
    <slot name="top" :expanded="expanded" :change="change"></slot>
    <div class="lg-collapse-body">
      <slot :expanded="expanded" :change="change"></slot>
    </div>
    <slot name="bottom" :expanded="expanded" :change="change"></slot>
  </div>
</template>

<script setup lang="ts">
import { ChevronDownIcon, ChevronRightIcon } from 'tdesign-icons-vue-next';
import { ref, watchEffect } from 'vue';

const emits = defineEmits(['change', 'update:modelValue']);
const props = defineProps({
  title: {
    type: String,
  },
  modelValue: {
    type: Boolean,
    default: false,
  },
  titleTrigger: {
    type: Boolean,
    default: true,
  },
  disabledTitle: {
    type: Boolean,
    default: false,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const expanded = ref(false);
watchEffect(() => {
  expanded.value = props.modelValue || props.disabled;
});

function clickTitle() {
  if (props.titleTrigger) {
    change();
  }
}

function change() {
  expanded.value = !expanded.value || props.disabled;
  emits('change', expanded.value);
  emits('update:modelValue', expanded.value);
}

defineExpose({
  change() {
    expanded.value = !expanded.value || props.disabled;
    emits('update:modelValue', expanded.value);
  },
  open() {
    expanded.value = true;
    emits('update:modelValue', expanded.value);
  },
  close() {
    expanded.value = false;
    emits('update:modelValue', expanded.value);
  },
});
</script>
<script lang="ts">
export default {
  name: 'LgCollapse',
};
</script>

<style scoped lang="less">
.lg-collapse {
  display: flex;
  flex-direction: column;
  .lg-collapse-header {
    display: flex;
    height: 40px;
    align-items: center;
  }
  .lg-collapse-right {
    text-align: right;
    flex: 1;
    cursor: pointer;
  }
  .lg-collapse-body {
    flex: 1;
    overflow: hidden;
  }
}
.lg-collapse-fold {
  .lg-collapse-body {
    max-height: 0 !important;
    display: none;
  }
}
.lg-collapse + .lg-collapse {
  border-top: 1px solid var(--td-component-border);
}
</style>
